'use client';

import { useState, useEffect, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import dynamic from 'next/dynamic';
import GlassCard from '@/components/ui/GlassCard';
import GlassButton from '@/components/ui/GlassButton';
import ConfirmDialog from '@/components/ui/ConfirmDialog';
import { notesApi, knowledgeBasesApi, documentsApi, chatApi } from '@/lib/api';
import toast from 'react-hot-toast';
import { 
  Save, 
  ArrowLeft, 
  Database,
  FileText,
  Zap,
  History,
  Sparkles,
  X,
  Check,
  Loader2
} from 'lucide-react';

// 动态导入 MDEditor 避免 SSR 问题
const MDEditor = dynamic(
  () => import('@uiw/react-md-editor'),
  { ssr: false }
);

interface Document {
  id: string;
  title: string;
  file_name: string;
}

interface KnowledgeBase {
  id: string;
  name: string;
}

interface NoteVersion {
  id: string;
  version_number: number;
  title: string;
  content: string;
  created_at: string;
}

function NoteEditorContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const noteId = searchParams?.get('id');

  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [selectedDocuments, setSelectedDocuments] = useState<string[]>([]);
  const [selectedKB, setSelectedKB] = useState<string>('');
  const [isVectorized, setIsVectorized] = useState(false);
  
  const [documents, setDocuments] = useState<Document[]>([]);
  const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
  const [versions, setVersions] = useState<NoteVersion[]>([]);
  
  const [showDocSelector, setShowDocSelector] = useState(false);
  const [showVersionHistory, setShowVersionHistory] = useState(false);
  const [showAIAssistant, setShowAIAssistant] = useState(false);
  
  const [saving, setSaving] = useState(false);
  const [vectorizing, setVectorizing] = useState(false);
  const [aiLoading, setAiLoading] = useState(false);
  const [restoreConfirm, setRestoreConfirm] = useState<{isOpen: boolean, versionId: string, versionNumber: number}>({
    isOpen: false,
    versionId: '',
    versionNumber: 0
  });

  useEffect(() => {
    loadKnowledgeBases();
    loadDocuments();
    if (noteId) {
      loadNote();
      loadVersions();
    }
  }, [noteId]);

  const loadNote = async () => {
    if (!noteId) return;
    try {
      const data = await notesApi.get(noteId);
      setTitle(data.title);
      setContent(data.content);
      setSelectedKB(data.knowledge_base_id || '');
      setIsVectorized(data.is_vectorized);
      setSelectedDocuments(data.documents?.map((d: any) => d.id) || []);
    } catch (error) {
      console.error('加载笔记失败:', error);
      toast.error('加载笔记失败');
    }
  };

  const loadKnowledgeBases = async () => {
    try {
      const resp = await knowledgeBasesApi.list();
      const list = Array.isArray(resp) ? resp : (resp?.items ?? []);
      setKnowledgeBases(list);
    } catch (error) {
      console.error('加载知识库失败:', error);
    }
  };

  const loadDocuments = async () => {
    try {
      const data = await documentsApi.list({ page: 1, page_size: 100 });
      setDocuments(data.items || []);
    } catch (error) {
      console.error('加载文档失败:', error);
    }
  };

  const loadVersions = async () => {
    if (!noteId) return;
    try {
      const data = await notesApi.getVersions(noteId);
      setVersions(data);
    } catch (error) {
      console.error('加载版本历史失败:', error);
    }
  };

  const handleSave = async () => {
    if (!title.trim()) {
      toast.error('请输入笔记标题');
      return;
    }

    try {
      setSaving(true);
      const noteData = {
        title,
        content,
        document_ids: selectedDocuments,
        knowledge_base_id: selectedKB || undefined,
      };

      if (noteId) {
        await notesApi.update(noteId, noteData);
        toast.success('保存成功');
        loadVersions(); // 重新加载版本历史
      } else {
        const newNote = await notesApi.create(noteData);
        toast.success('创建成功');
        router.push(`/dashboard/notes/editor?id=${newNote.id}`);
      }
    } catch (error: any) {
      toast.error('保存失败: ' + error.message);
    } finally {
      setSaving(false);
    }
  };

  const handleVectorize = async () => {
    if (!noteId) {
      toast.error('请先保存笔记');
      return;
    }
    if (!selectedKB) {
      toast.error('请先选择知识库');
      return;
    }

    try {
      setVectorizing(true);
      await notesApi.vectorize(noteId, selectedKB);
      setIsVectorized(true);
      toast.success('向量化成功！笔记已加入知识库，RAG问答可以检索到此笔记内容');
    } catch (error: any) {
      toast.error('向量化失败: ' + error.message);
    } finally {
      setVectorizing(false);
    }
  };

  const handleAISummary = async () => {
    if (selectedDocuments.length === 0) {
      toast.error('请先选择要总结的文档');
      return;
    }

    try {
      setAiLoading(true);
      const docTitles = documents
        .filter(d => selectedDocuments.includes(d.id))
        .map(d => d.title)
        .join('、');

      const prompt = `请总结以下文档的核心内容，形成结构化笔记：${docTitles}`;
      
      let aiResponse = '';
      await chatApi.sendMessageStream(
        prompt,
        (chunk) => {
          aiResponse += chunk;
        },
        () => {},
        () => {
          // 将AI总结追加到笔记内容
          const aiSection = `\n\n## 🤖 AI 总结（${new Date().toLocaleString('zh-CN')}）\n\n${aiResponse}\n\n`;
          setContent(content + aiSection);
          setShowAIAssistant(false);
        },
        (error) => {
          toast.error('AI 总结失败: ' + error);
        },
        {
          document_ids: selectedDocuments.join(','),
          temperature: 0.7,
          max_tokens: 2000
        }
      );
    } catch (error: any) {
      toast.error('AI 总结失败: ' + error.message);
    } finally {
      setAiLoading(false);
    }
  };

  const handleRestoreVersionClick = (versionId: string, versionNumber: number) => {
    setRestoreConfirm({ isOpen: true, versionId, versionNumber });
  };

  const handleRestoreVersionConfirm = async () => {
    const { versionNumber } = restoreConfirm;
    if (!noteId) return;

    try {
      const data = await notesApi.restoreVersion(noteId, versionNumber);
      setTitle(data.title);
      setContent(data.content);
      setShowVersionHistory(false);
      loadVersions();
      toast.success('版本恢复成功');
    } catch (error: any) {
      toast.error('恢复版本失败: ' + error.message);
    }
  };

  const toggleDocument = (docId: string) => {
    setSelectedDocuments(prev =>
      prev.includes(docId)
        ? prev.filter(id => id !== docId)
        : [...prev, docId]
    );
  };

  return (
    <div className="space-y-6">
      {/* 顶部工具栏 */}
      <div className="flex items-center justify-between">
        <GlassButton variant="secondary" onClick={() => router.push('/dashboard/notes')}>
          <ArrowLeft className="mr-2 h-5 w-5" />
          返回列表
        </GlassButton>
        
        <div className="flex gap-3">
          <GlassButton
            variant="secondary"
            onClick={() => setShowDocSelector(true)}
          >
            <FileText className="mr-2 h-5 w-5" />
            关联文档 ({selectedDocuments.length})
          </GlassButton>

          {noteId && (
            <GlassButton
              variant="secondary"
              onClick={() => setShowVersionHistory(true)}
            >
              <History className="mr-2 h-5 w-5" />
              版本历史
            </GlassButton>
          )}

          <GlassButton
            variant="secondary"
            onClick={() => setShowAIAssistant(true)}
            disabled={selectedDocuments.length === 0}
          >
            <Sparkles className="mr-2 h-5 w-5" />
            AI 辅助
          </GlassButton>

          <GlassButton
            variant="primary"
            onClick={handleSave}
            disabled={saving}
          >
            {saving ? (
              <>
                <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                保存中...
              </>
            ) : (
              <>
                <Save className="mr-2 h-5 w-5" />
                保存笔记
              </>
            )}
          </GlassButton>
        </div>
      </div>

      {/* 主编辑区域 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 左侧编辑器 */}
        <div className="lg:col-span-2 space-y-4">
          <GlassCard className="p-6">
            <input
              type="text"
              placeholder="笔记标题"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="w-full text-2xl font-bold bg-transparent border-none focus:outline-none text-gray-900 dark:text-white mb-4"
            />
            
            <div className="prose prose-sm max-w-none dark:prose-invert" data-color-mode="auto">
              <MDEditor
                value={content}
                onChange={(val) => setContent(val || '')}
                height={600}
                preview="live"
              />
            </div>
          </GlassCard>
        </div>

        {/* 右侧设置面板 */}
        <div className="space-y-4">
          <GlassCard className="p-6">
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
              笔记设置
            </h3>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-white/80 mb-2">
                  知识库
                </label>
                <select
                  value={selectedKB}
                  onChange={(e) => setSelectedKB(e.target.value)}
                  className="w-full px-3 py-2 bg-white/60 dark:bg-gray-800 border border-gray-300/40 dark:border-white/20 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/50 text-gray-900 dark:text-white"
                >
                  <option value="">私有笔记</option>
                  {knowledgeBases.map((kb) => (
                    <option key={kb.id} value={kb.id}>
                      {kb.name}
                    </option>
                  ))}
                </select>
                <p className="mt-1 text-xs text-gray-500 dark:text-white/50">
                  选择知识库后可向量化，让 AI 检索到此笔记
                </p>
              </div>

              {selectedKB && noteId && (
                <div>
                  <GlassButton
                    variant={isVectorized ? "secondary" : "primary"}
                    onClick={handleVectorize}
                    disabled={vectorizing}
                    className="w-full"
                  >
                    {vectorizing ? (
                      <>
                        <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                        向量化中...
                      </>
                    ) : isVectorized ? (
                      <>
                        <Check className="mr-2 h-5 w-5" />
                        已向量化
                      </>
                    ) : (
                      <>
                        <Zap className="mr-2 h-5 w-5" />
                        向量化笔记
                      </>
                    )}
                  </GlassButton>
                </div>
              )}

              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-white/80 mb-2">
                  统计信息
                </label>
                <div className="text-sm text-gray-600 dark:text-white/60 space-y-1">
                  <p>字数: {content.length}</p>
                  <p>关联文档: {selectedDocuments.length} 个</p>
                </div>
              </div>
            </div>
          </GlassCard>
        </div>
      </div>

      {/* 文档选择器弹窗 */}
      {showDocSelector && (
        <>
          <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50" onClick={() => setShowDocSelector(false)} />
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
            <GlassCard className="w-full max-w-2xl max-h-[80vh] overflow-y-auto p-6">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                  选择关联文档
                </h3>
                <button
                  onClick={() => setShowDocSelector(false)}
                  className="p-2 hover:bg-gray-100 dark:hover:bg-white/10 rounded-lg"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>

              <div className="space-y-2">
                {documents.map((doc) => (
                  <label
                    key={doc.id}
                    className="flex items-center gap-3 p-3 hover:bg-gray-50 dark:hover:bg-white/5 rounded-lg cursor-pointer"
                  >
                    <input
                      type="checkbox"
                      checked={selectedDocuments.includes(doc.id)}
                      onChange={() => toggleDocument(doc.id)}
                      className="rounded text-blue-500"
                    />
                    <div className="flex-1">
                      <p className="font-medium text-gray-900 dark:text-white">{doc.title}</p>
                      <p className="text-sm text-gray-500 dark:text-white/50">{doc.file_name}</p>
                    </div>
                  </label>
                ))}
              </div>

              <div className="mt-6 flex justify-end">
                <GlassButton variant="primary" onClick={() => setShowDocSelector(false)}>
                  确定 ({selectedDocuments.length} 个)
                </GlassButton>
              </div>
            </GlassCard>
          </div>
        </>
      )}

      {/* AI 辅助弹窗 */}
      {showAIAssistant && (
        <>
          <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50" onClick={() => setShowAIAssistant(false)} />
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
            <GlassCard className="w-full max-w-md p-6">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                  <Sparkles className="h-5 w-5 text-purple-500" />
                  AI 辅助
                </h3>
                <button
                  onClick={() => setShowAIAssistant(false)}
                  className="p-2 hover:bg-gray-100 dark:hover:bg-white/10 rounded-lg"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>

              <p className="text-sm text-gray-600 dark:text-white/60 mb-4">
                AI 将总结你选择的 {selectedDocuments.length} 个文档的核心内容，并生成结构化笔记追加到当前内容中。
              </p>

              <div className="flex gap-3">
                <GlassButton
                  variant="secondary"
                  onClick={() => setShowAIAssistant(false)}
                  className="flex-1"
                >
                  取消
                </GlassButton>
                <GlassButton
                  variant="primary"
                  onClick={handleAISummary}
                  disabled={aiLoading}
                  className="flex-1"
                >
                  {aiLoading ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      生成中...
                    </>
                  ) : (
                    <>
                      <Sparkles className="mr-2 h-4 w-4" />
                      开始生成
                    </>
                  )}
                </GlassButton>
              </div>
            </GlassCard>
          </div>
        </>
      )}

      {/* 版本历史弹窗 */}
      {showVersionHistory && (
        <>
          <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50" onClick={() => setShowVersionHistory(false)} />
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
            <GlassCard className="w-full max-w-4xl max-h-[80vh] overflow-y-auto p-6">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                  版本历史
                </h3>
                <button
                  onClick={() => setShowVersionHistory(false)}
                  className="p-2 hover:bg-gray-100 dark:hover:bg-white/10 rounded-lg"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>

              <div className="space-y-4">
                {versions.map((version, index) => (
                  <div
                    key={version.id}
                    className="p-4 bg-white/40 dark:bg-gray-800/40 rounded-lg hover:bg-white/60 dark:hover:bg-gray-800/60 transition-colors"
                  >
                    <div className="flex items-center justify-between mb-2">
                      <div>
                        <span className="font-semibold text-gray-900 dark:text-white">
                          版本 {version.version_number}
                          {index === 0 && (
                            <span className="ml-2 text-xs px-2 py-1 bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 rounded-full">
                              当前版本
                            </span>
                          )}
                        </span>
                        <p className="text-sm text-gray-500 dark:text-white/50">
                          {new Date(version.created_at).toLocaleString('zh-CN')}
                        </p>
                      </div>
                      {index !== 0 && (
                        <GlassButton
                          variant="secondary"
                          size="sm"
                          onClick={() => handleRestoreVersionClick(version.id, version.version_number)}
                        >
                          恢复此版本
                        </GlassButton>
                      )}
                    </div>
                    <p className="text-sm text-gray-600 dark:text-white/60 line-clamp-2">
                      {version.content.substring(0, 200)}...
                    </p>
                  </div>
                ))}
              </div>
            </GlassCard>
          </div>
        </>
      )}

      {/* 恢复版本确认对话框 */}
      <ConfirmDialog
        isOpen={restoreConfirm.isOpen}
        onClose={() => setRestoreConfirm({ isOpen: false, versionId: '', versionNumber: 0 })}
        onConfirm={handleRestoreVersionConfirm}
        title="恢复版本"
        message={`确定要恢复到版本 ${restoreConfirm.versionNumber} 吗？当前内容将被覆盖。`}
        confirmText="恢复"
        cancelText="取消"
        variant="warning"
      />
    </div>
  );
}

export default function NoteEditorPage() {
  return (
    <Suspense fallback={<div className="flex justify-center items-center h-screen">加载中...</div>}>
      <NoteEditorContent />
    </Suspense>
  );
}

